package org.petstore.web.servlet;

import org.petstore.domain.Account;
import org.petstore.util.Cart;
import org.petstore.service.AccountService;
import org.petstore.service.CartService;
import org.petstore.service.impl.AccountServiceImpl;
import org.petstore.service.impl.CartServiceImpl;
import org.petstore.web.servlet.util.MyUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import static org.petstore.web.servlet.util.ServletUtil.LOGIN_FORM;
import static org.petstore.web.servlet.util.ServletUtil.MAIN_FORM;

public class LoginServlet extends HttpServlet {

    AccountService accountService = MyUtil.getApplicationContext().getBean("accountService", AccountService.class);
    CartService cartService = MyUtil.getApplicationContext().getBean("cartService", CartService.class);

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String code1 = request.getParameter("code");
        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();

        //验证验证码是否正确
        //验证码不区分大小写 (equalsIgnoreCase)
        if (!code1.equalsIgnoreCase(session.getAttribute("code1").toString())) {
            request.setAttribute("msg", "验证码错误");
            request.getRequestDispatcher(LOGIN_FORM).forward(request, response);
        }


        //验证账号与密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Account loginUser = accountService.login(username, password);

        if (loginUser == null) {
            request.setAttribute("msg", "用户名或密码错误");
            request.getRequestDispatcher(LOGIN_FORM).forward(request, response);
        } else {
            //登录成功
            Cart cart;
            cart = cartService.getCartByName(loginUser.getUsername());
            //个人信息读取到session中
            session.setAttribute("loginUser", loginUser);
            session.setAttribute("cart", cart);
            request.getRequestDispatcher(MAIN_FORM).forward(request, response);
        }
    }
}
